package com.tianyang.yukuaifu.business.main.fragment;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tianyang.yukuaifu.R;
import com.tianyang.yukuaifu.base.BaseFragment;
import com.tianyang.yukuaifu.business.auth.provider.AuthOpenProvider;
import com.tianyang.yukuaifu.business.main.adapter.MyAdapter;
import com.tianyang.yukuaifu.business.main.bean.MyBean;
import com.tianyang.yukuaifu.business.main.bean.UserCenterOutput;
import com.tianyang.yukuaifu.business.main.contract.MainConfig;
import com.tianyang.yukuaifu.business.main.contract.MyContract;
import com.tianyang.yukuaifu.business.main.presenter.MyPresenter;
import com.tianyang.yukuaifu.business.main.provider.MainOpenProvider;
import com.tianyang.yukuaifu.business.main.view.MainActivity;
import com.tianyang.yukuaifu.business.trade.bean.TradeTotalOutput;
import com.tianyang.yukuaifu.business.trade.provider.TradeOpenProvider;
import com.tianyang.yukuaifu.common.cache.CacheManage;
import com.tianyang.yukuaifu.common.cache.CacheModel;
import com.tianyang.yukuaifu.common.utils.CommonViewUtils;
import com.tianyang.yukuaifu.jump.eventbus.RefreshUserEvent;
import com.tianyang.yukuaifu.module.dialog.HintDialog;
import com.tianyang.yukuaifu.module.dialog.RemindDialog;
import com.tianyang.yukuaifu.module.dialog.interfaces.TwoBtnClickListener;
import com.tianyang.yukuaifu.utils.SystemBarHelper;
import com.tianyang.yukuaifu.utils.VerifyUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description：我的
 */

public class MyFragment extends BaseFragment implements MyContract.View {

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.srl)
    SmartRefreshLayout srl;
    @BindView(R.id.usernameTv)
    TextView usernameTv;
    @BindView(R.id.phoneTv)
    TextView phoneTv;
    @BindView(R.id.posStatusShowTv)
    TextView posStatusShowTv;
    @BindView(R.id.posStatusTv)
    TextView posStatusTv;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.amountTv)
    TextView amountTv;
    @BindView(R.id.countTv)
    TextView countTv;
    @BindView(R.id.userNumberTv)
    TextView userNumberTv;
    @BindView(R.id.posChannelTv)
    TextView posChannelTv;

    private MyAdapter vMyAdapter;

    private MyContract.Presenter mPresenter;

    private boolean isSignType;//是否签约

    private UserCenterOutput mOutput;

    private MyBean empowerBean, merchantRateBean, signTypeBean;

    private List<MyBean> listDataView = new ArrayList<>();

    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initView() {
        super.initView();
        int barHeight = SystemBarHelper.getStatusBarHeight(getContext());
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) topView.getLayoutParams();
        params.height = barHeight;
        topView.setLayoutParams(params);

        String identity = CacheManage.getInstance().getCache(CacheModel.IDENTITY, MainConfig.IDENTITY_MERCHANT);
        if (TextUtils.equals(MainConfig.IDENTITY_MERCHANT, identity)) {
            titleTv.setText("星渝付");
        }

        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4));
        vMyAdapter = new MyAdapter();
        recyclerView.setAdapter(vMyAdapter);

        mPresenter = new MyPresenter(this);
        mPresenter.getTradeRecordList();
    }

    @Override
    protected void initData() {
        super.initData();
        empowerBean = new MyBean("商户授权", R.drawable.ic_mine_8, R.id.empowerRl);
        merchantRateBean = new MyBean("商户费率", R.drawable.ic_mine_9, R.id.merchantRateRl);
        signTypeBean = new MyBean("商户签约", R.drawable.ic_mine_10, R.id.signTypeRl);
        listDataView.add(new MyBean("收款工具", R.drawable.ic_mine_1, R.id.myMp));
        listDataView.add(new MyBean("商户信息", R.drawable.ic_mine_2, R.id.merchantInfoRl));
        listDataView.add(new MyBean("结算卡号", R.drawable.ic_mine_3, R.id.settleNoRl));
        listDataView.add(new MyBean("交易明细", R.drawable.ic_mine_4, R.id.tradeRecordRl));
//        listDataView.add(new MyBean("结算管理", R.drawable.ic_mine_3, R.id.settleManageRl));
        listDataView.add(new MyBean("店铺管理", R.drawable.ic_mine_7, R.id.storeManageRl));
        listDataView.add(new MyBean("帮助中心", R.drawable.ic_mine_5, R.id.helpCenterRl));
        listDataView.add(new MyBean("我的设置", R.drawable.ic_mine_6, R.id.rlSettingCenter));
        vMyAdapter.setNewData(listDataView);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void showTradeTotalView(JSONObject jsonObject) {
        if (srl.isRefreshing())
            srl.finishRefresh();
        if (jsonObject != null) {
            TradeTotalOutput output = JSON.parseObject(jsonObject.toJSONString(), TradeTotalOutput.class);
            if (output != null) {
                if (!TextUtils.isEmpty(output.getTotalAmount())) {
                    amountTv.setText(VerifyUtil.decimalFormat(output.getTotalAmount()));
                }
                countTv.setText(output.getTradeCount() + "");
                userNumberTv.setText(output.getUserNumber() + "");
            }
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        srl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.getTradeRecordList();
                EventBus.getDefault().post(new RefreshUserEvent());
            }
        });
        vMyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MyBean bean = ((MyAdapter)adapter).getItem(position);
                if (bean != null) {
                    switch (bean.getId()) {
                        case R.id.empowerRl:
                            if (mOutput == null) {
                                EventBus.getDefault().post(new RefreshUserEvent());
                                return;
                            }
                            AuthOpenProvider.getInstance().openMerchantEmpowerActivity(getContext(), mOutput.getUsername());
                            break;
                        case R.id.signTypeRl:
                            if (mOutput == null) {
                                EventBus.getDefault().post(new RefreshUserEvent());
                                return;
                            }
                            if (!isSignType) {
                                MainOpenProvider.getInstance().openBrowserX5Activity(getContext(), mOutput.getSignType(), true);
                            }
                            break;
                        case R.id.myMp:
                            if (mOutput == null) {
                                EventBus.getDefault().post(new RefreshUserEvent());
                                return;
                            }
                            if (mOutput.getPosStatus() > 1) {
                                MainOpenProvider.getInstance().openDeviceListActivity(getContext());
//                                if (TextUtils.isEmpty(mOutput.getSn()))
//                                    MainOpenProvider.getInstance().openBindCodePlateActivity(getContext());
//                                else
//                                    MainOpenProvider.getInstance().openMyCodePlateActivity(getContext());
                            } else {
                                new HintDialog(getContext())
                                        .title("温馨提示")
                                        .content("请先完成商户入网审核流程！")
                                        .show();
                            }
                            break;
                        case R.id.merchantInfoRl:
                            if (mOutput == null) {
                                EventBus.getDefault().post(new RefreshUserEvent());
                                return;
                            }
                            if (mOutput.getPosStatus() != 0)
                                AuthOpenProvider.getInstance().openAuthByMchType(getContext(), mOutput.getMerchantType(),
                                        String.valueOf(mOutput.getPosStatus()),true, mOutput.getUsername());
                            else
                                showRemindDialog("温馨提示", "请先提交商户资料入网");
                            break;
                        case R.id.settleNoRl:
                            if (mOutput == null) {
                                EventBus.getDefault().post(new RefreshUserEvent());
                                return;
                            }
                            if (mOutput.getPosStatus() > 1)
                                TradeOpenProvider.getInstance().openBankManageActivity(getContext(), false);
                            else if (mOutput.getPosStatus() == 1)
                                new HintDialog(getContext())
                                        .title("审核中")
                                        .content("您上传的入网资料正在审核中，请耐心等待")
                                        .show();
                            else
                                showRemindDialog("温馨提示", "商户入网未审核通过，请提交入网资料");
                            break;
                        case R.id.settleManageRl:
                            if (mOutput == null) {
                                EventBus.getDefault().post(new RefreshUserEvent());
                                return;
                            }
                            if (mOutput.getPosStatus() > 1)
                                TradeOpenProvider.getInstance().openSettleMethodActivity(getContext());
                            else if (mOutput.getPosStatus() == 1)
                                new HintDialog(getContext())
                                        .title("审核中")
                                        .content("您上传的入网资料正在审核中，请耐心等待")
                                        .show();
                            else
                                showRemindDialog("温馨提示", "商户入网未审核通过，请提交入网资料");
                            break;
                        case R.id.storeManageRl:
                            MainOpenProvider.getInstance().openStoreManageActivity(getContext());
                            break;
                        case R.id.merchantRateRl:
                            if (mOutput == null) {
                                EventBus.getDefault().post(new RefreshUserEvent());
                                return;
                            }
                            if (mOutput.getPosStatus() > 1)
                                MainOpenProvider.getInstance()
                                        .openRateConfigActivity(getContext(), mOutput.getUsername(), 0,false);
                            else if (mOutput.getPosStatus() == 1)
                                new HintDialog(getContext())
                                        .title("审核中")
                                        .content("您上传的入网资料正在审核中，请耐心等待")
                                        .show();
                            else
                                showRemindDialog("温馨提示", "商户入网未审核通过，请提交入网资料");
                            break;
                        case R.id.helpCenterRl:
                            MainOpenProvider.getInstance().openHelpCenterActivity(getContext());
                            break;
                        case R.id.rlSettingCenter:
                            MainOpenProvider.getInstance().openSettingCenterActivity(getContext());
                            break;
                        case R.id.tradeRecordRl:
                            TradeOpenProvider.getInstance().openTradeRecordActivity(getContext());
                            break;
                    }
                }
            }
        });
    }

    @OnClick({R.id.authRl})
    public void onClick(View view) {
        if (!isRespondEvent() || getContext() == null) return;
        if (view.getId() == view.getId()) {
            if (mOutput == null) {
                EventBus.getDefault().post(new RefreshUserEvent());
                return;
            }
            if (mOutput.getPosStatus() == 0) {
//                String identity = CacheManage.getInstance().getCache(CacheModel.IDENTITY, MainConfig.IDENTITY_MERCHANT);
//                if (TextUtils.equals(MainConfig.IDENTITY_MERCHANT, identity)) {
//                    AuthOpenProvider.getInstance().openAuthByMchType(getContext(), mOutput.getMchType(),
//                            String.valueOf(mOutput.getPosStatus()), false, mOutput.getPhone());
//                } else {
                    AuthOpenProvider.getInstance().openAuthSelectTypeActivity(getContext(), true);
//                }
            } else if (mOutput.getPosStatus() < 0) {
                showRemindDialog("认证失败", TextUtils.isEmpty(mOutput.getFailResult()) ? "商户进件失败" : mOutput.getFailResult());
            } else if (mOutput.getPosStatus() == 1) {
                new HintDialog(getContext())
                        .title("审核中")
                        .content("您上传的入网资料正在审核中，请耐心等待")
                        .show();
            } else if (mOutput.getPosStatus() == 2 || mOutput.getPosStatus() == 3) {
                AuthOpenProvider.getInstance().openMerchantEmpowerActivity(getContext(), mOutput.getUsername());
            }
        }
    }

    private void showRemindDialog(String title, String content) {
        new RemindDialog(getContext())
                .title(title)
                .content(content)
                .cancel("再等一等")
                .comfirm("立即认证")
                .listener(new TwoBtnClickListener() {
                    @Override
                    public void onLeftClick() {

                    }

                    @Override
                    public void onRightClick() {
                        AuthOpenProvider.getInstance().openAuthSelectTypeActivity(getContext(), true);
                    }
                })
                .show();
    }

    @Override
    public void onResume() {
        super.onResume();
        UserCenterOutput output = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (output != null) {
            showViewByData(output);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEntity(UserCenterOutput event) {
        if (event != null) {
            showViewByData(event);
        }
    }

    /**
     * 根据数据显示view
     */
    @SuppressLint("SetTextI18n")
    private void showViewByData(UserCenterOutput output) {
        if (output == null) return;
        mOutput = output;
        if (!TextUtils.isEmpty(output.getRealName())) {
            usernameTv.setText("用户名：" + output.getRealName());
        } else {
            usernameTv.setText("用户名：" + VerifyUtil.checkString(output.getUsername()));
        }
        phoneTv.setText("手机号：" + VerifyUtil.secretPhoneNumber(output.getPhone()));
        posChannelTv.setText("渠　道：" + VerifyUtil.checkString(output.getPosChannelName()));
        isSignType = CommonViewUtils.isSignType(output.getSignType());
        List<MyBean> beanList = new ArrayList<>();
        if (output.getPosStatus() >= 2) {
            beanList.add(empowerBean);
        }
        if (!isSignType) {
            beanList.add(signTypeBean);
        }
        beanList.addAll(listDataView);
        if (output.isShowRate()) {
            beanList.add(beanList.size()-2, merchantRateBean);
        }
        vMyAdapter.setNewData(beanList);
        switch (output.getPosStatus()) {
            case -4:
                posStatusShowTv.setText("复审驳回，认证后可享受更多特权功能");
                posStatusTv.setText("查看原因");
                break;
            case -3:
                posStatusShowTv.setText("复审待审核，审核通过后可享受更多特权功能");
                posStatusTv.setText("查看");
                break;
            case -2:
            case -1:
                posStatusShowTv.setText("初审驳回，认证后可享受更多特权功能");
                posStatusTv.setText("查看原因");
                break;
            case 0:
                posStatusShowTv.setText("待提交，提交后可享受更多特权功能");
                posStatusTv.setText("去认证");
                break;
            case 1:
//                if (!isSignType) {
//                    posStatusShowTv.setText("待签约，签约后可享受更多特权功能");
//                    posStatusTv.setText("去签约");
//                } else {
                    posStatusShowTv.setText("审核中，审核后可享受更多特权功能");
                    posStatusTv.setText("查看");
//                }
                break;
            case 2:
                posStatusShowTv.setText("待授权，授权后可享受更多特权功能");
                posStatusTv.setText("去授权");
                break;
            case 3:
                posStatusShowTv.setText("已绑定，享受多项特权功能");
                posStatusTv.setText("去授权");
                break;
            case 4:
                posStatusShowTv.setText("已认证，享受多项特权功能");
                posStatusTv.setText("已认证");
                break;
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    public void setPresenter(MyContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void showLoadingDialog(boolean cancelable) {
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).showLoadingDialog(cancelable);
        }
    }

    @Override
    public void showLoadingDialog(boolean cancelable, String content) {
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).showLoadingDialog(cancelable, content);
        }
    }

    @Override
    public void dismissLoadingDialog() {
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).dismissLoadingDialog();
        }
    }

    @Override
    public void showErrorText(Throwable e) {
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).showErrorText(e);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
